<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>入庫單</span>
        <el-button class="buttonA" type="success" @click="onSubmit">保存入庫單</el-button>
      </div>
      <el-form ref="forms" :model="form" label-width="auto" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="倉庫" prop="depotId">
              <el-select
                v-model="form.depotId"
                remote
                reserve-keyword
                style="width: 200px;"
              >
                <el-option
                  v-for="item in depotOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供應商">
              <el-select
                v-model="form.vendorId"
                placeholder="請選擇供應商"
                style="width: 200px;"
                filterable
                clearable
              >
                <el-option
                  v-for="item in list"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="採購單號">
              <el-input
                v-model="form.sourceNo"
                style="width: 200px;"
                suffix-icon="el-icon-search"
                @focus="dialogVisible = true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入庫時間">
              <div class="block">
                <el-date-picker
                  v-model="form.inTime"
                  type="datetime"
                  placeholder="選擇日期時間"
                  :value-format="'yyyy-MM-dd HH:mm:ss'"
                  style="width: 200px;"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款狀態">
              <el-select
                v-model="form.paymentStatus"
                clearable
                style="width: 200px;"
              >
                <el-option
                  v-for="item in dict.stockPaymentStatus"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.dictKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="備註">
              <el-input
                v-model="form.description"
                type="textarea"
                :rows="1"
                style="width: 200px"
                placeholder="請輸入內容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入庫單金額" prop="fillAmount">
              <el-input v-model="form.fillAmount" style="width: 200px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣率">
              <div>
                <el-input
                  v-model.number="form.discountRate"
                  style="width: 200px;"
                  @keyup.enter.native="amount"
                  @input="disableFlag = true;amount"
                />
                %
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="校驗誤差值">
              <el-input v-model="form.otherFee" style="width: 200px;" @blur="amount" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单类型: ">
              <el-select
                v-model="form.inType"
                clearable
                style="width: 200px;"
              >
                <el-option
                  v-for="item in dict.inBillType"
                  :key="item.id"
                  :label="item.dictValue"
                  :value="item.dictKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="核驗金額: " class="grayItem">
              <span style="color: rgb(182,182,182)">{{ form.amount }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <div slot="header" class="clearfix">
        <span>入庫商品明細</span>
        <el-button class="buttonB" type="primary" @click="choose">
          添加商品
        </el-button>
        <el-button class="buttonC" type="warning" icon="el-icon-check" @click="discount" />
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        height="400px"
      >
        <el-table-column
          prop="nameCn"
          label="產品名"
          width="300px"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.nameCn }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="sku"
          label="商品編號"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.sku }}</span></template>
        </el-table-column>
        <el-table-column
          prop="upc"
          label="條形碼"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.product.upc }}</span></template>
        </el-table-column>

        <el-table-column
          prop="stock"
          label="剩余庫存"
        >
          <template slot-scope="scope">
            {{ scope.row.product.stock }}
          </template>
        </el-table-column>

        <el-table-column
          prop="originalPrice"
          label="Price"
        >
          <template slot-scope="scope">
            {{ scope.row.originalPrice }}
          </template>
        </el-table-column>

        <el-table-column
          prop="originalPrice"
          label="PR"
        >
          <template slot-scope="scope">
            {{ scope.row.pr }}
          </template>
        </el-table-column>

        <el-table-column
          prop="quantity"
          label="數量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.quantity" />
          </template>
        </el-table-column>

        <el-table-column
          prop="price"
          label="單件成本價"
          align="center"
          width="100px"
        >
          <template slot-scope="scope">
            <el-autocomplete
              v-model="scope.row.price"
              :fetch-suggestions="
                (queryString, cb) => {
                  querySearch(queryString, cb, scope.row);
                }
              "
              placeholder="成本價"
              @change="
                (value) => {
                  countPr(value,scope.row);
                }
              "
              @select="
                (item) => {
                  countPr(item.value,scope.row);
                }
              "
            >
              <template slot-scope="{ item }">
                <div
                  style="text-overflow: ellipsis;overflow: hidden;"
                >{{ item.label }}
                </div>
              </template>
            </el-autocomplete>
          </template>
        </el-table-column>

        <el-table-column
          prop="inUnitQuantity"
          label="單位數量"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.product.inUnitQuantity" />
          </template>
        </el-table-column>
        <el-table-column
          prop="expireDate"
          label="過期時間"
          width="130"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.expireDate"
              placeholder="yyyy-mm-dd"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="earlyWarningDate"
          label="預警時間"
          width="130"
        >
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.earlyWarningDate"
              placeholder="yyyy-mm-dd"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="備註"
        >
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click.native.prevent="deleteRow(scope.$index, tableData)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" width="70%" title="選擇採購單">
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <el-input
              v-model="query.code"
              clearable
              placeholder="訂單編號"
              style="width: 185px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-select
              v-model="query.vendorId"
              placeholder="請選擇供應商"
              filterable
              clearable
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in list"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <date-range-picker v-model="modelCreatedAt" class="date-item" :fix-date.sync="query.createTime" />
            <!-- 搜索 -->
            <rrOperation :crud="crud" />
          </div>
          <crudOperation :permission="permission">
            <template #left>
              <el-button
                type="primary"
                class="filter-item"
                size="mini"
                @click="addPurchaseItems"
              >添加
              </el-button>
              <el-button
                class="filter-item"
                size="mini"
                @click="dialogVisible=false"
              >取消
              </el-button>
            </template>
          </crudOperation>
        </div>
        <el-table
          ref="purchaseTable"
          v-loading="crud.loading"
          :data="crud.data"
          style="width: 100%;height: 500px"
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
          />
          <el-table-column
            prop="code"
            label="採購訂單編碼"
          />
          <el-table-column
            prop="description"
            label="採購訂單描述"
          />
          <el-table-column
            prop="estimateDeliveryDate"
            label="創建時間"
          />
          <el-table-column
            prop="vendorId"
            label="供應商"
          />
        </el-table>
        <pagination />
      </el-dialog>
    </el-card>
    <choose-product ref="chooseProduct" :vendor="form.vendorId" @childNotify="childNotify" />
  </div>
</template>

<script>
import api from '@/api/wms/depotBillIn'
import depotApi from '@/api/wms/depot'
import chooseProduct from '@/components/product/index'
import Vue from 'vue'
import router from '@/router/routers'
import store from '@/store'
import vendorApi from '@/api/cms/vendor'
import CRUD, { crud, header, presenter } from '@crud/crud'
import crudPurchase from '@/api/erp/purchase'
import pagination from '@crud/Pagination'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import DateRangePicker from '@/components/DateRangePicker'
import Date from '@/utils/datetime.js'

export default {
  name: 'CreatPurchaseInBill',
  dicts: ['inBillType', 'stockPaymentStatus'],
  components: { chooseProduct, rrOperation, crudOperation, pagination, DateRangePicker },
  mixins: [presenter(), header(), crud()],
  props: {
    model: {
      type: String,
      default: 'add'
    }
  },
  cruds() {
    return CRUD({
      title: '入庫單', url: 'purchase/page', query: { 'deleteStatus': false }, sort: 'id:desc',
      crudMethod: { ...crudPurchase }, optShow: {
        add: false,
        edit: false,
        del: false,
        download: false,
        reset: false
      }
    })
  },
  data() {
    return {
      modelCreatedAt: '',
      restaurants: [],
      permission: {
        add: ['admin', 'product:add'],
        edit: ['admin', 'product:edit'],
        del: ['admin', 'product:del']
      },
      tableData: [],
      dialogVisible: false,
      depotTypeOptions: [{ label: '採購入庫', value: 2 }],
      depotOptions: [],
      newArr: [],
      arrId: [],
      list: [],
      loading: false,
      disableFlag: true,
      form: {
        paymentStatus: '',
        description: '',
        vendorId: null,
        sourceNo: '',
        sourceId: null,
        sumQuantity: '',
        inType: '',
        id: null,
        inTime: '',
        depotId: null,
        discountRate: 0,
        shipping: 0,
        otherFee: 0,
        amount: 0,
        fillAmount: 0,
        depotBillInItems: []
      },
      tempRoute: {},
      rules: {
        depotId: [
          { required: true, message: '请选择倉庫', trigger: 'change' }
        ],
        fillAmount: [
          { required: true, message: '请填寫入庫單金額', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    vendorApi.getAll().then(res => {
      for (let i = 0; i < res.data.length; i++) {
        this.list.push({ label: res.data[i].name, value: res.data[i].id })
      }
    })
    depotApi.page().then(res => {
      for (let i = 0; i < res.data.rows.length; i++) {
        this.depotOptions.push({ label: res.data.rows[i].name, value: res.data.rows[i].id })
      }
    })
  },
  created() {
    const date = new Date()
    this.form.inTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
      date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
    const id = this.$route.params.id
    if (id === 'add') {
      this.setTitle('新增商品入庫單')
    } else {
      api.getOne(id).then(res => {
        this.setTitle('修改商品入庫單')
        const purchaseItem = res.data
        this.form.inType = purchaseItem.inType
        this.form.inTime = purchaseItem.inTime
        this.form.amount = purchaseItem.amount
        this.form.paymentStatus = purchaseItem.paymentStatus
        this.form.vendorId = purchaseItem.vendorId
        this.form.sourceId = purchaseItem.sourceId
        this.form.depotId = purchaseItem.depot.id
        this.form.otherFee = purchaseItem.otherFee
        this.form.discountRate = purchaseItem.discountRate
        this.form.description = purchaseItem.description
        this.form.sourceNo = purchaseItem.sourceNo
        this.form.sumQuantity = purchaseItem.sumQuantity
        this.form.amount = purchaseItem.amount
        this.form.fillAmount = purchaseItem.fillAmount
        this.tableData = purchaseItem.depotBillInItems
        this.tableData.map((item) => {
          item.originalPrice = !item.product.price && item.product.price !== 0 ? item.product.originalPrice : item.product.price
          const pr = (item.originalPrice - item.price) / item.price
          item.pr = Math.round(pr * 10000) / 100 + '%'
          return item
        })
      })
    }
  },
  methods: {
    amount() {
      let amount = 0
      let amountNum = 0
      if (isNaN(this.form.discountRate)) {
        this.form.discountRate = 0
      }
      if (isNaN(this.form.otherFee)) {
        this.form.otherFee = 0
      }
      for (let i = 0; i < this.tableData.length; i++) {
        if (isNaN(this.tableData[i].price)) {
          this.tableData[i].price = 0
        }
        if (isNaN(this.tableData[i].quantity)) {
          this.tableData[i].quantity = 0
        }
        if (isNaN(this.tableData[i].amount)) {
          this.tableData[i].amount = 0
        }
        amountNum += this.tableData[i].quantity
        this.form.sumQuantity = amountNum
        this.tableData[i].amount = this.tableData[i].price * this.tableData[i].quantity
        amount += this.tableData[i].amount
        this.form.amount = amount.toFixed(2)
      }
    },
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.purchaseTable.clearSelection()
        this.$refs.purchaseTable.toggleRowSelection(selection.pop())
      }
    },

    discount() {
      for (let i = 0; i < this.tableData.length; i++) {
        if (isNaN(this.tableData[i].price)) {
          this.tableData[i].price = 0
        }
        if (isNaN(this.tableData[i].quantity)) {
          this.tableData[i].quantity = 0
        }
        if (isNaN(this.form.discountRate)) {
          this.form.discountRate = 0
        }
        if (isNaN(this.form.otherFee)) {
          this.form.otherFee = 0
        }
        if (this.form.discountRate !== 0) {
          this.tableData[i].price = this.tableData[i].price * (1 - this.form.discountRate / 100)
          const numStr = this.tableData[i].price.toString()
          const index = numStr.indexOf('.')
          if (index !== -1) {
            const result = numStr.slice(0, index + 3)
            this.tableData[i].price = result
          }
        }
      }
      this.amount()
      this.form.otherFee = (this.form.fillAmount - this.form.amount).toFixed(2)
      this.disableFlag = false
    },

    setTitle(title) {
      Vue.nextTick(() => {
        const routeTitle = Object.assign(Object.assign({}, router.currentRoute), { title })
        store.dispatch('tagsView/updateVisitedView', routeTitle)
        document.title = title
      })
    },
    childNotify(params) {
      if (params.length === 0) {
        this.$message.error('請選擇商品')
      } else {
        for (const item of params) {
          if (this.arrId.indexOf(item.product.id) === -1) {
            this.arrId.push(item.product.id)
            this.tableData.push({
              ...item,
              quantity: 0,
              inUnitQuantity: 0,
              originalPrice: !item.product.price && item.product.price !== 0 ? item.product.originalPrice : item.product.price,
              price: '',
              pr: '0%'
            })
          }
        }
        this.$refs.chooseProduct.close()
      }
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    onSubmit() {
      this.$refs.forms.validate((valid) => {
        if (valid) {
          if (this.form === null) {
            this.$message.error('請填寫入庫單')
            return
          }
          this.form.depotBillInItems = this.tableData
          this.form.inType = 0
          if (this.form.depotBillInItems.length === 0) {
            this.$message.error('請填寫入庫單詳情')
            return
          }
          this.amount()
          this.form.id = this.$route.params.id
          const addEditData = []
          const pattern = /(\d{4})(\d{2})(\d{2})/
          for (let i = 0; i < this.tableData.length; i++) {
            let expireDate = this.tableData[i].expireDate
            let earlyWarningDate = this.tableData[i].earlyWarningDate
            console.log(expireDate)
            console.log(earlyWarningDate)
            if (expireDate !== undefined && expireDate !== '' && expireDate !== null) {
              expireDate = expireDate.replace(pattern, '$1-$2-$3')
              if (expireDate.match(/^(\d{4})(-)(\d{2})(-)(\d{2})$/) == null) {
                this.$message.error('第' + (i + 1) + '行過期時間日期格式錯誤，请检查')
                return
              }
            }
            if (earlyWarningDate !== undefined && earlyWarningDate !== '' && earlyWarningDate !== null) {
              earlyWarningDate = earlyWarningDate.replace(pattern, '$1-$2-$3')
              if (earlyWarningDate.match(/^(\d{4})(-)(\d{2})(-)(\d{2})$/) == null) {
                this.$message.error('第' + (i + 1) + '行預警時間日期格式錯誤，请检查')
                return
              }
            }
            addEditData.push(
              {
                'productId': this.tableData[i].product.id,
                'inUnitQuantity': this.tableData[i].inUnitQuantity,
                'price': this.tableData[i].price,
                'surplusQuantity': this.tableData[i].surplusQuantity,
                'id': this.form.id === 'add' ? null : this.tableData[i].id,
                'expireDate': expireDate,
                'earlyWarningDate': earlyWarningDate,
                'depotBillInId': this.tableData[i].depotBillInId,
                'quantity': this.tableData[i].quantity,
                'remark': this.tableData[i].remark
              })
          }
          this.form.depotBillInItems = addEditData
          if (this.form.id === 'add') {
            this.form.id = null
            api.add(this.form).then(() => {
              this.tableData = []
              this.form = {}
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.replace('/wms/purchaseDeptos')
            })
          } else {
            api.edit(this.form).then(() => {
              this.tableData = []
              this.form = {}
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.replace('/wms/purchaseDeptos')
            })
          }
        } else {
          return false
        }
      })
    },
    choose() {
      this.$refs.chooseProduct.open()
    },
    addPurchaseItems() {
      const currentSelect = this.$refs.purchaseTable.selection
      if (currentSelect.length > 1) {
        this.$message.warning('請選擇單個採購單')
        return
      }
      if (currentSelect.length === 0) {
        this.$message.warning('請選擇採購單')
        return
      }
      this.tableData = currentSelect[0].purchaseItems
      this.tableData.map((item) => {
        item.originalPrice = !item.product.price && item.product.price !== 0 ? item.product.originalPrice : item.product.price
        item.pr = '0%'
        return item
      })
      console.log(this.tableData)
      this.form.sourceNo = currentSelect[0].code
      this.form.sourceId = currentSelect[0].id
      this.dialogVisible = false
    },

    // 计算利润率  PR (profit rate) = (Price-cost)/Cost %
    countPr(value, row) {
      if (value > 0) {
        const pr = (row.originalPrice - value) / value
        row.pr = Math.round(pr * 10000) / 100 + '%'
      }
    },

    priceCheck(row) {
      this.restaurants = []
      api.priceCheck({ 'productId': row.product.id }).then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          this.restaurants.push(
            { 'value': res.data[i].price.toString(), 'label': res.data[i].depotBillInCode + '-- $' + res.data[i].price }
          )
        }
      })
    },
    querySearch(queryString, cb, row) {
      this.priceCheck(row)
      const restaurants = this.restaurants
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    }
  }
}
</script>

<style scoped>

.productInfo span {
  display: block;
  line-height: 16px;
}

.buttonA {
  right: 5%;
  position: absolute;
}

.buttonB {
  right: 10%;
  position: absolute;
}

.buttonC {
  right: 5%;
  position: absolute;
}

</style>
